package com.meiyu.live.ui.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.meiyu.live.BaseActivity;
import com.meiyu.live.R;
import com.meiyu.live.comm.Constant;
import com.meiyu.live.comm.UserConfig;
import com.meiyu.live.eventbus.LoginEvent;
import com.meiyu.live.net.param.LoginParams;
import com.meiyu.live.net.param.ThirdLoginParams;
import com.meiyu.live.net.response.LoginResponse;
import com.meiyu.live.util.ToastUtil;
import com.meiyu.live.widget.NetLoadingDailog;

import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;

/**
 * Created by zbl on 2016/8/28.
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private static final int REQUEST_CODE_REGISTER = 10;
    private static final int REQUEST_CODE_RESETPASSWORD = 10;

    protected NetLoadingDailog dialog_loading;
    private View btn_back, btn_register, btn_forget, btn_login_qq, btn_login_wechat, btn_login_sina;
    private TextView btn_login;
    private EditText et_account, et_password;

    private UMShareAPI mShareAPI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mShareAPI = UMShareAPI.get(this);
        init();
    }

    private void init() {
        dialog_loading = new NetLoadingDailog(this);
        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(this);
        btn_login = (TextView) findViewById(R.id.btn_login);
        btn_login.setOnClickListener(this);
        btn_login.setEnabled(false);
        btn_register = findViewById(R.id.btn_register);
        btn_register.setOnClickListener(this);
        btn_forget = findViewById(R.id.btn_forget);
        btn_forget.setOnClickListener(this);

        btn_login_qq = findViewById(R.id.btn_login_qq);
        btn_login_qq.setOnClickListener(this);
        btn_login_wechat = findViewById(R.id.btn_login_wechat);
        btn_login_wechat.setOnClickListener(this);
        btn_login_sina = findViewById(R.id.btn_login_sina);
        btn_login_sina.setOnClickListener(this);

        et_account = (EditText) findViewById(R.id.et_account);
        et_password = (EditText) findViewById(R.id.et_password);
        et_account.addTextChangedListener(textWatcher);
        et_password.addTextChangedListener(textWatcher);
        et_account.setText(UserConfig.getInstance().getLogingAccount());
//        et_account.setText(UserConfig.getInstance().getLogingPassword());
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (et_account.getText().length() > 0 && et_password.getText().length() > 0) {
//                btn_login.setTextColor(0xff593512);
                btn_login.setBackgroundResource(R.drawable.background_btn_startlive);
                btn_login.setEnabled(true);
            } else {
//                btn_login.setTextColor(0xffffffff);
                btn_login.setBackgroundResource(R.drawable.background_login_disable);
                btn_login.setEnabled(false);
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (UserConfig.getInstance().getParams() != null) {
                UserConfig.getInstance().setParams(null);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View view) {
        if (view == btn_back) {
            if (UserConfig.getInstance().getParams() != null) {
                UserConfig.getInstance().setParams(null);
            }
            finish();
        } else if (view == btn_login) {
            getData(et_account.getText().toString().trim(), et_password.getText().toString().trim());
        } else if (view == btn_register) {
            startActivity(RegisterActivity.class, REQUEST_CODE_REGISTER);
        } else if (view == btn_forget) {
            startActivity(ResetPasswordActivity.class, REQUEST_CODE_RESETPASSWORD);
        } else if (view == btn_login_qq) {
            doThirdLogin(SHARE_MEDIA.QQ);
        } else if (view == btn_login_wechat) {
            doThirdLogin(SHARE_MEDIA.WEIXIN);
        } else if (view == btn_login_sina) {
            doThirdLogin(SHARE_MEDIA.SINA);
        }
    }

    public void doThirdLogin(SHARE_MEDIA platform) {
        dialog_loading.loading();
        mShareAPI.doOauthVerify(this, platform, umAuthListener);
    }


    private void getData(final String account, final String password) {
        if (TextUtils.isEmpty(account)) {
            ToastUtil.show("请输入账号");
            return;
        } else if (TextUtils.isEmpty(password)) {
            ToastUtil.show("请输入密码");
            return;
        }
        long accountNumber = 0;
        try {
            accountNumber = Long.parseLong(account);
        } catch (NumberFormatException e) {
            ToastUtil.show("请输入正确的账号");
            return;
        }
        dialog_loading.loading();
        final long accountnumber = accountNumber;
        request(new LoginParams(accountNumber, password, JPushInterface.getRegistrationID(getApplicationContext())), LoginResponse.class, new Response.Listener<LoginResponse>() {
            @Override
            public void onResponse(LoginResponse loginResponse) {
                dialog_loading.dismissDialog();
                if (loginResponse != null && loginResponse.getStatusCode() == Constant.StatusCode_Success) {
                    UserConfig.getInstance().setSession_token(loginResponse.getSession_token());
                    UserConfig.getInstance().setNet_ease(loginResponse.getNet_ease());
                    UserConfig.getInstance().setNet_token(loginResponse.getNet_token());
                    UserConfig.getInstance().setUserId(accountnumber);
                    Log.e("UserConfig", "setNet_token: " + loginResponse.getNet_token());

                    UserConfig.getInstance().setLogingAccount(account);
                    UserConfig.getInstance().setLogingPassword(password);

                    ToastUtil.show("登录成功");
                    EventBus.getDefault().post(new LoginEvent(true));
                    setResult(RESULT_OK);
                    finish();
                } else {
                    ToastUtil.show(loginResponse.getMsg());
                }
            }
        });
    }

    private void getDataThird(final String third_id, final String platform, final String name, final String sex, final String avatar, final String uid) {
        request(new ThirdLoginParams(third_id, platform, name, sex, avatar, JPushInterface.getUdid(this), uid), LoginResponse.class, new Response.Listener<LoginResponse>() {
            @Override
            public void onResponse(LoginResponse loginResponse) {
                dialog_loading.dismissDialog();
                if (loginResponse.getStatusCode() == Constant.StatusCode_Success) {
                    UserConfig.getInstance().setSession_token(loginResponse.getSession_token());
                    UserConfig.getInstance().setNet_ease(loginResponse.getNet_ease());
                    UserConfig.getInstance().setNet_token(loginResponse.getNet_token());
                    UserConfig.getInstance().setUserId(loginResponse.getUid());

                    UserConfig.getInstance().setOpenId(third_id);
                    UserConfig.getInstance().setThirdPlatform(platform);
                    UserConfig.getInstance().setThirdName(name);
                    UserConfig.getInstance().setThirdAvatar(avatar);
                    UserConfig.getInstance().setSex(sex);
                    UserConfig.getInstance().setUid(uid);

                    ToastUtil.show("登录成功");
                    EventBus.getDefault().post(new LoginEvent(true));
                    setResult(RESULT_OK);
                    finish();
                } else {
                    ToastUtil.show(loginResponse.getMsg());
                }
            }
        });
        Log.e("deviceId", JPushInterface.getUdid(this));
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onError() {
        super.onError();
        dialog_loading.dismissDialog();
        ToastUtil.show("登录失败");
    }

    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            if (action == UMAuthListener.ACTION_AUTHORIZE) {
                //授权成功后，获取信息
                mShareAPI.getPlatformInfo(LoginActivity.this, platform, umAuthListener);
//                getDataThird();
            } else if (action == UMAuthListener.ACTION_GET_PROFILE) {
                if (data != null) {
                    String openId = data.get("openid");
                    String name = data.get("screen_name");
                    String avatar = data.get("profile_image_url");
                    String sex = data.get("gender");
                    String uid = null;
                    String platformString;
                    if (platform == SHARE_MEDIA.QQ) {
                        platformString = "qq";
                        if (sex.equals("男")) {
                            sex = "m";
                        } else {
                            sex = "f";
                        }
                    } else if (platform == SHARE_MEDIA.WEIXIN) {
                        platformString = "wechat";
                        uid = data.get("unionid");
                        if (sex.equals("1")) {
                            sex = "m";
                        } else {
                            sex = "f";
                        }
                    } else if (platform == SHARE_MEDIA.SINA) {
                        platformString = "sina";
                        openId = data.get("idstr");
                    } else {
                        platformString = "";
                    }
                    getDataThird(openId, platformString, name, sex, avatar, uid);
                }
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            dialog_loading.dismissDialog();
            Toast.makeText(getApplicationContext(), "登录失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            dialog_loading.dismissDialog();
            Toast.makeText(getApplicationContext(), "取消登录", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_REGISTER) {
            if (resultCode == RESULT_OK && data != null) {
                et_account.setText(data.getStringExtra("account"));
                et_password.setText(data.getStringExtra("password"));
            }
        }
    }
}
